package com.mpgame.common.handler;

import com.mpgame.common.proto.*;
import com.mpgame.common.utils.Log;
import com.mpgame.common.manager.HeartbeatMgr;

import io.netty.channel.ChannelHandlerContext;

public class HeartbeatHandler extends BaseHandler{
    public HeartbeatHandler(){
        super("HeartbeatHandler", 10, true);
    }
    @Override
    public boolean handle(ChannelHandlerContext ctx, GamePacket pkt){
        if(pkt.getCmd() == CmdId.HEARTBEAT_REQ){
            handleHeartbeatReq(ctx, pkt);
            return true;
        }
        else if(pkt.getCmd() == CmdId.HEARTBEAT_RSP){
            handleHeartbeatRsp(ctx, pkt);
            return true;
        }
        return false;
    }

    private void handleHeartbeatReq(ChannelHandlerContext ctx, GamePacket pkt){
        Log.info("收到心跳请求，发送心跳响应...");
        GamePacket rsp = GamePacket.newBuilder()
            .setEc(ErrorCode.SUCCESS)
            .setCmd(CmdId.HEARTBEAT_RSP)
            .build();
        ctx.writeAndFlush(rsp);
    }

    private void handleHeartbeatRsp(ChannelHandlerContext ctx, GamePacket pkt){
        Log.info("收到心跳响应，连接正常...");
        // 通知心跳管理器已收到响应
        HeartbeatMgr.notifyHeartbeatResponse();
    }
}
